package org.flower.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author Aizen
 */
public class BaseDao {
	static DataSource dataSource = null;
	static {
		try {
			Properties prop = new Properties();
			prop.load(BaseDao.class.getClassLoader().getResourceAsStream("druid.properties"));
			dataSource = DruidDataSourceFactory.createDataSource(prop);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行增删改操作
	 * @param sql  要执行的sql语句
	 * @param objs 要替换sql中?的具体值
	 * @return 受影响的行数
	 */
	public boolean executeUpdate(String sql,Object...objs) {
		int result = 0;
		PreparedStatement stmt = null;
		try {
			stmt = dataSource.getConnection().prepareStatement(sql);
			if(objs!=null&&objs.length>0) {
				for(int i=0;i<objs.length;i++) {
					stmt.setObject((i+1), objs[i]);
				}
			}
			result = stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				closeAll(null,stmt,stmt.getConnection());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result>0;
	}
	/**
	 * 执行查询 
	 * @param sql  
	 * @param objs
	 * @return 查询到的结果集
	 */
	public ResultSet executeQuery(String sql,Object...objs) {
		ResultSet rs = null;
		try {
			PreparedStatement stmt = dataSource.getConnection().prepareStatement(sql);
			if(objs!=null&&objs.length>0) {
				for (int i = 0; i < objs.length; i++) {
					stmt.setObject((i+1), objs[i]);
				}
			}
			rs = stmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}	
		return rs;
	}
	/**
	 * 关闭对象，释放资源
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	public void closeAll(ResultSet rs,Statement stmt,Connection conn) {
		try {
				if(rs!=null) {
					rs.close();
				}
				if(stmt!=null&&!stmt.isClosed()) {
					stmt.close();
				}
				if(conn!=null&&!conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		
	}
}
















